package com.wenye.Controller;


import com.wenye.myMVC.core.annotation.Controller;
import com.wenye.myMVC.mvc.RequestHandlerChain;
import com.wenye.myMVC.mvc.annotation.RequestMapping;
import com.wenye.myMVC.mvc.annotation.RequestMethod;
import com.wenye.myMVC.mvc.annotation.RequestParam;
import com.wenye.myMVC.mvc.bean.ModelAndView;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping(value = "/file")
public class PageController {

    @RequestMapping(value = "/uploadfile",method = RequestMethod.GET)
    public String uploadfile(){
        System.out.println("say");
        return "index.jsp";
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(@RequestParam(value = "file") File file) throws IOException {
        String filename = null;
        String temp[] = file.getPath().replaceAll("\\\\","/").split("/");
        if (temp.length > 1) {
            filename = temp[temp.length - 1];
        }
        saveFile(file,filename);
        return "success.html";
    }

    private void saveFile(File file,String filename) throws IOException {
        FileInputStream fin = new FileInputStream(file);
        FileOutputStream fout = new FileOutputStream("D:\\uploadfiles\\"+filename);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = fin.read(buf)) > 0) {
            fout.write(buf, 0, bytesRead);
        }
        fin.close();
        fout.flush();
        fout.close();
    }
}
